#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    Part of Seagull - The Pyhon Pages engine
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    url_translations:
      Convert URLs from internal to external URLs and back again.
"""
__author__ = 'Jonathan Slenders <jonathan at slenders dot be>'
__license__ = 'GNU LGPL'



import posixpath
from configuration import SystemConfig

# TODO: Other protocols than HTTP


# Global variable
_system_config = SystemConfig()

def page_to_url(page, reference_page=u'/index'):
	"""
	Transforms the URL for a page into an absolute URL
	starting with a slash

	The full url is calculated against the
	reference_page, or if none is given, the pages root
	directory.
	"""
	assert(reference_page[0] == '/')
	assert(isinstance(page, unicode))
	assert(isinstance(reference_page, unicode))

	global _system_config

	if page[0:1] in ('#', '?'):
		return page
	elif page[0:2] == '//': # Absolute, including domain name
		return page
	elif page[0:7] in ('http://') or page[0:8] in ('https://'): # Absolute, including protocol and domain
		return page
	elif page[0:1] == '/': # Absolute starting at pages directory
		return _system_config.url_prefix + page
	else: # Relative to current page
		return _system_config.url_prefix + posixpath.normpath(posixpath.join(reference_page, u'..', page))

def page_to_full_url(page, reference_page=u'/index'):
	"""
	Like page_to_url, but returns a URL starting with http://
	"""
	global _system_config

	if page[0:1] in ('#', '?'):
		return page
	elif _system_config.port == 80:
		return 'http://%s%s' % (_system_config.domain,
				page_to_url(page, reference_page=reference_page))
	else:
		return 'http://%s:%s%s' % (_system_config.domain, _system_config.port,
				page_to_url(page, reference_page=reference_page))
	
def url_to_page(url):
	"""
	Returns the matching page for this URL
	Should return somthing starting with '/',
	which is the root of the pages directory.

	Returns always unicode
	"""
	global _system_config

	# Absolute URLs without domain part (/index)
	if url.startswith('/'):
		result = url

	# URLs with domain, but without protocol (//host.com/index)
	elif url.startswith('//'):
		# Drop the slashes
		url = url.replace('//', '', 1)

		# Drop hostname (everything before the first '/')
		if url.find('/'):
			url = url[url.find('/'):]
		else:
			raise InvalidUrlException()

		# Lookup the URL, again
		result = url_to_page(url)
		
	# Full URLs (http://host.com/index)
	elif url.startswith('http:'):
		# Drop protocol
		url = url.replace('http:', '', 1)
		
		# Lookup the URL, again
		result = url_to_page(url)

	# Make sure to return unicode
	if isinstance(url, str):
		url = url.decode('utf-8')

	# Drop the url prefix
	prefix = _system_config.url_prefix
	if result[0:len(prefix)] == prefix:
		result = result[len(prefix):]

	# Make sure the result starts with /
	if result[0:1] == u'/':
		return result
	else:
		return u'/%s' % result


class InvalidUrlException(Exception):
	pass
